import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/entity/banner_for_home_entity.dart';
import 'package:taonile/routers/routers.dart';
import 'package:taonile/utils/common_utils.dart';

import '../entity/announcement_list_entity.dart';
import '../entity/goods_area_category_entity.dart';
import '../entity/goods_source_list_entity.dart';
import '../entity/jingang_for_home_entity.dart';
import '../entity/product_entity.dart';
import '../http/api.dart';
import '../views/home_index_top_layout.dart';
import '../views/mall_home_module.dart';
import '../views/marquee_widget.dart';

class HomeIndex extends StatefulWidget {
  const HomeIndex({Key? key}) : super(key: key);

  @override
  State<HomeIndex> createState() => _HomeIndexState();
}

class _HomeIndexState extends State<HomeIndex> {
  //推荐商品
  List<ProductData> datas = [];
  var page = 1;

  //报单专区的配置
  List<GoodsAreaCategoryData> goodsAreaCates = [];

  //金刚区
  List<JingangForHomeData> jingangList = [];

  //轮播
  List<BannerForHomeData> banners = [];

  //公告
  List<AnnouncementListDataData> announce = [];

  //模块配置
  List<GoodsSourceListData> sourceList = [];

  var menus = [];
  var menusSub = [];
  int currentMenuIndex = 0;
  bool isLoopBanner = false;

  // //做局部刷新，手动触发式
  // GlobalKey<HomeIndexTopLayoutState> homeTopKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  getData() async {
    // menus.add('电脑办公');
    // menus.add('美妆护肤');
    // menus.add('家具家装');
    // menus.add('内衣配饰');
    // menus.add('运动户外');
    // menus.add('食品酒饮');
    // menus.add('二手商品');
    //
    // menusSub.add('Computer');
    // menusSub.add('Beauty');
    // menusSub.add('Furniture');
    // menusSub.add('Underwear');
    // menusSub.add('Exercise');
    // menusSub.add('Foodstuff');
    // menusSub.add('Second');

    await getBannerList();
    await getAnnounce();
    await getJingangList();
    await getAreaCategoryList();
    await getGoodsAreaCategory();
    await getProducts();
  }

  getBannerList() async {
    dynamic result = await Api.bannerForHome({});
    BannerForHomeEntity entity = BannerForHomeEntity.fromJson(result);
    setState(() {
      banners.clear();
      banners.addAll(entity.data);
      Future.delayed(const Duration(milliseconds: 1500), () {
        setState(() {
          isLoopBanner = true;
        });
      });
    });
  }

  getAnnounce() async {
    dynamic result = await Api.announcementList({'page': '1', 'limit': '20'});
    AnnouncementListEntity entity = AnnouncementListEntity.fromJson(result);
    setState(() {
      if (entity.code == 1) {
        announce.clear();
        announce.addAll(entity.data.data);
      }
    });
  }

  getJingangList() async {
    dynamic result = await Api.jingangForHome();
    JingangForHomeEntity entity = JingangForHomeEntity.fromJson(result);
    setState(() {
      jingangList.clear();
      jingangList.addAll(entity.data);
    });
  }

  getAreaCategoryList() async {
    dynamic result = await Api.goodsAreaCategoryList();
    GoodsAreaCategoryEntity entity = GoodsAreaCategoryEntity.fromJson(result);
    setState(() {
      goodsAreaCates.clear();
      goodsAreaCates.addAll(entity.data);
    });
  }

  getGoodsAreaCategory() async {
    dynamic result = await Api.goodsSourceList();
    GoodsSourceListEntity entity = GoodsSourceListEntity.fromJson(result);
    setState(() {
      sourceList.clear();
      sourceList.addAll(entity.data);
    });
  }

  getProducts() async {
    dynamic result = await Api.goodsList({'page': page.toString(), 'size': '20', 'area_id': '2'});
    ProductEntity entity = ProductEntity.fromJson(result);
    setState(() {
      if (page == 1) {
        datas.clear();
      }
      if (entity.data.isNotEmpty) {
        page++;
        datas.addAll(entity.data);
      }
    });
  }

  //返回商品列表item
  getListItem(int index) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.productDetail, params: {'productId': datas[index].id});
      },
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(10.w),
        ),
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(10.w),
                topRight: Radius.circular(10.w),
              ),
              child: CachedNetworkImage(
                imageUrl: CommonUtils.compressImageUrl(datas[index].mainImg, 500, 500),
                fit: BoxFit.fill,
                width: double.infinity,
                height: 330.w,
                errorWidget: (context, url, error) {
                  return Image.asset(
                    'assets/images/bg_default_400.png',
                    width: double.infinity,
                    height: 330.w,
                    fit: BoxFit.fill,
                  );
                },
              ),
            ),
            Padding(padding: EdgeInsets.all(5.w)),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              // decoration: const BoxDecoration(color: Config.tr),
              width: double.infinity,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(padding: EdgeInsets.only(top: 2.w)),
                  Text(
                    datas[index].name,
                    softWrap: false,
                    style: TextStyle(color: Config.colorText1, fontSize: 28.sp),
                  ),
                  Padding(padding: EdgeInsets.only(top: 10.w)),
                  Text(
                    CommonUtils.formatAmountUnit(datas[index].money, datas[index].company,
                        datas[index].money1, datas[index].company1),
                    softWrap: false,
                    style: TextStyle(color: Colors.redAccent, fontSize: 24.sp),
                  ),
                  Padding(padding: EdgeInsets.only(top: 10.w)),
                  InkWell(
                    onTap: () {
                      Routes.navigateTo(context, Routes.mallHome,
                          params: {'storeId': datas[index].storeId});
                    },
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          datas[index].store.name,
                          softWrap: false,
                          style: TextStyle(color: Config.colorText1, fontSize: 24.sp),
                        ),
                        Text(
                          '进店 >',
                          softWrap: false,
                          style: TextStyle(color: Config.colorText1, fontSize: 24.sp),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget getJingangItem(int index, Function() onTap) {
    return InkWell(
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CachedNetworkImage(
            imageUrl: CommonUtils.compressImageUrl(jingangList[index].imgPath, 100, 100),
            fit: BoxFit.fill,
            width: 75.w,
            height: 75.w,
            errorWidget: (context, url, error) {
              return Image.asset(
                'assets/images/bg_default_400.png',
                width: 75.w,
                height: 75.w,
                fit: BoxFit.fill,
              );
            },
          ),
          Padding(
            padding: EdgeInsets.only(top: 8.w),
          ),
          Text(jingangList[index].name,
              style: TextStyle(fontSize: 21.sp, color: Config.colorText1)),
        ],
      ),
    );
  }

  //返回菜单item
  getMenuItem(int position) {
    return InkWell(
      onTap: () {
        setState(() {
          currentMenuIndex = position;
        });
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(18.w, 0, 18.w, 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(padding: EdgeInsets.all(5.w)),
            currentMenuIndex == position
                ? Text(
                    menus[position],
                    style: TextStyle(color: (Config.colorMain), fontSize: 30.sp),
                  )
                : Text(
                    menus[position],
                    style: TextStyle(color: (Config.colorText1), fontSize: 30.sp),
                  ),
            currentMenuIndex == position
                ? Text(
                    menusSub[position],
                    style: TextStyle(color: (Config.colorMain), fontSize: 23.sp),
                  )
                : Text(
                    menusSub[position],
                    style: TextStyle(color: (Config.colorText3), fontSize: 23.sp),
                  ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // ScrollController controller = ScrollController();
    // controller.addListener(() {
    //   if (controller.offset > 100) {
    //     return;
    //   }
    //   // print("监听滚动的位置 ${controller.offset}");
    //   homeTopKey.currentState?.upDateLayoutBg(controller.offset / 100);
    // });

    return Scaffold(
      body: Container(
        padding: const EdgeInsets.all(0),
        width: double.infinity,
        decoration: const BoxDecoration(color: Config.colorBg2),
        height: double.infinity,
        child: Stack(
          children: [
            Container(
              margin: EdgeInsets.only(top: 160.w),
              child: EasyRefresh.builder(
                header: const MaterialHeader(),
                footer: const MaterialFooter(),
                onRefresh: () async {
                  await getBannerList();
                  await getAnnounce();
                  await getJingangList();
                  await getAreaCategoryList();
                  await getGoodsAreaCategory();
                  page = 1;
                  await getProducts();
                },
                onLoad: () async {
                  await getProducts();
                },
                childBuilder: (context, physics) {
                  return ListView(
                    scrollDirection: Axis.vertical,
                    // controller: controller,
                    padding: EdgeInsets.only(top: 0.w),
                    physics: physics,
                    children: [
                      Container(
                        //轮播
                        margin: EdgeInsets.only(left: 25.w, right: 25.w),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10.w),
                        ),
                        height: 306.w,
                        child: ClipRRect(
                          borderRadius: BorderRadius.circular(10.w),
                          child: Swiper(
                            itemBuilder: (BuildContext context, int index) {
                              return CachedNetworkImage(
                                imageUrl:
                                    CommonUtils.compressImageUrl(banners[index].imgPath, 750, 350),
                                fit: BoxFit.fill,
                                errorWidget: (context, url, error) {
                                  return Image.asset(
                                    'assets/images/bg_default_400.png',
                                    width: 700.w,
                                    height: 306.w,
                                    fit: BoxFit.fill,
                                  );
                                },
                              );
                            },
                            onTap: (index) {
                              // Routes.navigateTo(context, Routes.webView, params: {
                              //   'pageTitle': banners[index].id,
                              //   'webUrl': banners[index].link
                              // });
                            },
                            autoplayDelay: 4000,
                            autoplay: isLoopBanner,
                            loop: isLoopBanner,
                            layout: SwiperLayout.DEFAULT,
                            itemCount: banners.length,

                            // viewportFraction: 0.7,
                            // scale: 0.8,
                            pagination: SwiperPagination(
                              builder: DotSwiperPaginationBuilder(
                                  // size: Size(20.w, 4.w),
                                  // activeSize: Size(20.w, 4.w),
                                  size: 15.w,
                                  activeSize: 15.w,
                                  activeColor: Config.colorMain,
                                  color: Config.colorWhite),
                            ),
                          ),
                        ),
                      ),
                      Container(
                        height: 90.w,
                        margin: EdgeInsets.only(top: 30.w, left: 25.w, right: 25.w),
                        padding: EdgeInsets.symmetric(horizontal: 20.w),
                        decoration: BoxDecoration(
                          color: Config.colorWhite,
                          borderRadius: BorderRadius.circular(12.w),
                        ),
                        child: InkWell(
                          onTap: () {
                            Routes.router.navigateTo(context, Routes.announcement,
                                transition: TransitionType.inFromRight);
                          },
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  Image.asset(
                                    'assets/images/icon_home_notice.png',
                                    width: 32.w,
                                    height: 32.w,
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(left: 20.w),
                                  ),
                                  SizedBox(
                                    height: 36.w,
                                    width: 400.w,
                                    child: MarqueeWidget(
                                      //子Item构建器
                                      itemBuilder: (BuildContext context, int index) {
                                        String itemStr =
                                            announce.isNotEmpty ? announce[index].title : '';
                                        //通常可以是一个 Text文本
                                        return Text(
                                          itemStr,
                                          style: TextStyle(fontSize: 26.w),
                                        );
                                      },
                                      //循环的提示消息数量
                                      count: announce.length,
                                      loopSeconds: 4,
                                    ),
                                  ),
                                ],
                              ),
                              Icon(
                                Icons.arrow_forward_ios,
                                size: 25.w,
                                color: Config.colorText3,
                              ),
                            ],
                          ),
                        ),
                      ),
                      Container(
                        //金刚区
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 30.w),
                        child: SizedBox(
                          height: jingangList.length > 5 ? 280.w : 130.w,
                          child: GridView.builder(
                            padding: EdgeInsets.symmetric(vertical: 0.w, horizontal: 0.w),
                            physics: const NeverScrollableScrollPhysics(),
                            scrollDirection: Axis.vertical,
                            itemCount: jingangList.length,
                            itemBuilder: (context, index) {
                              return getJingangItem(index, () async {
                                // Routes.navigateTo(context, Routes.webView, params: {
                                //   'pageTitle': jingangList[index].name,
                                //   'webUrl': jingangList[index].link
                                // });
                                Routes.navigateTo(context, Routes.productList,
                                    params: {'cateId': jingangList[index].cateId});
                              });
                            },
                            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                              mainAxisSpacing: 0.w,
                              childAspectRatio: 1,
                              crossAxisSpacing: 0,
                              crossAxisCount: 5,
                            ),
                          ),
                        ),
                      ),
                      // getMallHomeModule1(
                      //     'https://img.zcool.cn/community/01abc85a9e162aa801219586dc141c.jpg@1280w_1l_2o_100sh.jpg'),
                      getMallHomeModule3Special(context, goodsAreaCates),
                      getMallHomeModule4(context, sourceList),
                      // getMallHomeModule6(
                      //     'https://n.sinaimg.cn/finance/transform/184/w630h354/20220905/dd76-db80ee162c520a218bdd7e698e0b5714.jpg',
                      //     'https://pad.mydrivers.com/img/20170510/0dfa56aeace14b49959052d1c6ec6c9d.jpg',
                      //     'https://img2.baidu.com/it/u=3066156497,2399437797&fm=253&fmt=auto&app=138&f=JPG?w=400&h=300',
                      //     'https://img2.baidu.com/it/u=407732994,1382908239&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=506',
                      //     'https://pic1.zhimg.com/v2-6438843a4cbae9184b935a75a5059ac6_1440w.jpg?source=172ae18b',
                      //     'https://img2.baidu.com/it/u=1323202793,3644150238&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'),
                      // getMallHomeModule5(
                      //   'https://pics6.baidu.com/feed/b7003af33a87e950d990202d55d1144bf9f2b4da.jpeg?token=f7aadb16068f7accdf1bca5d1679bbe1',
                      //   'https://img2.baidu.com/it/u=3066156497,2399437797&fm=253&fmt=auto&app=138&f=JPG?w=400&h=300',
                      //   'https://pic1.zhimg.com/v2-6438843a4cbae9184b935a75a5059ac6_1440w.jpg?source=172ae18b',
                      //   'https://img0.baidu.com/it/u=1707266565,2130578631&fm=253&fmt=auto&app=120&f=JPEG?w=667&h=500',
                      //   'https://img2.baidu.com/it/u=407732994,1382908239&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=506',
                      // ),
                      // getMallHomeModuleToday(),
                      Container(
                        margin: EdgeInsets.only(top: 40.w, left: 25.w, right: 25.w),
                        child: Row(
                          children: [
                            Text('推荐商品',
                                style: TextStyle(color: (Config.colorText1), fontSize: 30.sp)),
                          ],
                        ),
                      ),
                      // Container(
                      //   width: double.infinity,
                      //   margin: EdgeInsets.only(top: 25.w),
                      //   height: 100.w,
                      //   child: ListView.builder(
                      //     itemCount: menus.length,
                      //     padding: EdgeInsets.only(left: 10.w, right: 15.w),
                      //     shrinkWrap: true,
                      //     scrollDirection: Axis.horizontal,
                      //     physics: const BouncingScrollPhysics(),
                      //     itemBuilder: (BuildContext context, int index) {
                      //       return getMenuItem(index);
                      //     },
                      //   ),
                      // ),
                      Container(
                        margin: EdgeInsets.fromLTRB(20.w, 30.w, 20.w, 20.w),
                        decoration: const BoxDecoration(color: Colors.transparent),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              width: double.infinity,
                              child: GridView.builder(
                                padding: EdgeInsets.symmetric(horizontal: 0.w),
                                itemCount: datas.length,
                                shrinkWrap: true,
                                scrollDirection: Axis.vertical,
                                physics: const NeverScrollableScrollPhysics(),
                                itemBuilder: (BuildContext context, int index) {
                                  return getListItem(index);
                                },
                                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 2,
                                    mainAxisSpacing: 19.w,
                                    crossAxisSpacing: 19.w,
                                    childAspectRatio: 0.71),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            HomeIndexTopLayout(
                // key: homeTopKey,
                ),
          ],
        ),
      ),
    );
  }
}
